<template>
  <div class="deposit-history-page">
    <div class="page-container">
      <div class="content-container">
        <div class="history-content">
          <!-- Header -->
          <div class="history-header">
            <h1 class="history-title">{{ $t('pages.deposit.historyTitle') }}</h1>
            <el-button 
              class="back-btn"
              @click="goBack"
              size="small"
            >
              {{ $t('pages.deposit.backButton') }}
            </el-button>
          </div>

          <!-- History List -->
          <div class="history-list" v-loading="isLoading">
            <div 
              v-for="record in depositRecords" 
              :key="record.id"
              class="history-item"
            >
              <div class="record-info">
                <div class="record-type">
                  {{ $t('pages.deposit.depositRecord') }} {{ formatAmount(record.amount) }}
                </div>
                <div
                  class="record-meta"
                  v-if="record.lockedNearAmount > 0"
                >
                  <span class="near-value">
                    {{ $t('pages.deposit.lockedNearShort', { near: formatNear(record.lockedNearAmount) }) }}
                  </span>
                  <span class="near-price" v-if="record.lockedNearPrice > 0">
                    (@ ₩{{ formatNearPrice(record.lockedNearPrice) }}/NEAR)
                  </span>
                </div>
                <div class="record-date">
                  {{ record.date }}
                </div>
              </div>
              <div class="record-status">
                <el-tag 
                  :type="getStatusType(record.status)"
                  class="status-tag"
                >
                  {{ getStatusText(record.status) }}
                </el-tag>
              </div>
            </div>

            <!-- Empty State -->
            <div v-if="depositRecords.length === 0" class="empty-state">
              <div class="empty-icon">📋</div>
              <div class="empty-text">{{ $t('pages.deposit.emptyStateText') }}</div>
              <div class="empty-description">{{ $t('pages.deposit.emptyStateDescription') }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { api, type ApiResponse } from '@/utils/request'

const router = useRouter()
const { t } = useI18n()

// 충값记录接口类型
interface DepositRecord {
  id: number
  amount: number
  lockedNearAmount: number
  lockedNearPrice: number
  date: string
  status: 'pending' | 'completed' | 'failed'
}

// 充值记录数据
const depositRecords = ref<DepositRecord[]>([])
const isLoading = ref(false)

// 格式化金额显示
const formatAmount = (amount: number): string => {
  return amount.toLocaleString('ko-KR')
}

const formatNear = (amount: number): string => {
  return amount.toLocaleString('ko-KR', { minimumFractionDigits: 4, maximumFractionDigits: 4 })
}

const formatNearPrice = (price: number): string => {
  return price.toLocaleString('ko-KR', { minimumFractionDigits: 0, maximumFractionDigits: 2 })
}

// 获取状态标签类型
const getStatusType = (status: string): string => {
  switch (status) {
    case 'confirmed':
    case 'completed':
      return 'success'
    case 'pending':
      return 'warning'
    case 'failed':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string): string => {
  switch (status) {
    case 'confirmed':
    case 'completed':
      return t('pages.deposit.statusCompleted')
    case 'pending':
      return t('pages.deposit.statusPending')
    case 'failed':
      return t('pages.deposit.statusFailed')
    default:
      return t('pages.deposit.statusUnknown')
  }
}

// 返回上一页
const goBack = (): void => {
  router.back()
}

// 加载充值历史
const loadDepositHistory = async () => {
  try {
    isLoading.value = true
    const response = await api.get<{
      records: any[]
      summary: any
      pagination: any
    }>('/api/deposit/history')

    if (response.success) {
      depositRecords.value = response.data.records.map((record: any) => ({
        id: record.id,
        amount: typeof record.amount === 'number' ? record.amount : 0,
        lockedNearAmount: typeof record.lockedNearAmount === 'number' ? record.lockedNearAmount : 0,
        lockedNearPrice: typeof record.lockedNearPrice === 'number' ? record.lockedNearPrice : 0,
        date: record.createdAt ? new Date(record.createdAt).toLocaleString('ko-KR') : '-',
        status: (record.status || '').toLowerCase()
      }))
    }
  } catch (error) {
    console.error('충전 내역 로드 실패:', error)
    ElMessage.error('충전 내역을 불러오지 못했습니다')
  } finally {
    isLoading.value = false
  }
}

// 页面初始化
onMounted(() => {
  document.title = '입출금 현황 - MyNearWallet'
  loadDepositHistory()
})
</script>

<style scoped lang="scss">
.deposit-history-page {
  background: white;
  min-height: 100vh;
  padding: 0;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0;
}

.content-container {
  max-width: 800px;
  margin: 0 auto;
}

.history-content {
  background: white;
  border-radius: 16px;
  margin: 24px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  overflow: hidden;

  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #e2e8f0;
    background: white;

    .history-title {
      font-size: 20px;
      font-weight: 600;
      color: #1a202c;
      margin: 0;
    }

    .back-btn {
      background: white;
      border: 1px solid #d1d5db;
      color: #374151;
      padding: 6px 12px;
      font-size: 14px;
      border-radius: 6px;

      &:hover {
        border-color: #7c3aed;
        color: #7c3aed;
        background: rgba(124, 58, 237, 0.05);
      }
    }
  }

  .history-list {
    .history-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 24px;
      background: white;
      border-bottom: 1px solid #f1f5f9;
      transition: background 0.2s ease;

      &:hover {
        background: #f8fafc;
      }

      &:last-child {
        border-bottom: none;
      }

      .record-info {
        flex: 1;

        .record-type {
          font-size: 16px;
          font-weight: 500;
          color: #1a202c;
          margin-bottom: 4px;
        }

        .record-meta {
          font-size: 13px;
          color: #64748b;
          margin-bottom: 4px;

          .near-price {
            margin-left: 6px;
          }
        }

        .record-date {
          font-size: 14px;
          color: #64748b;
        }
      }

      .record-status {
        .status-tag {
          font-weight: 500;
          border: none;

          &.el-tag--warning {
            background: #fbbf24;
            color: #1a202c;
          }

          &.el-tag--success {
            background: #10b981;
            color: white;
          }

          &.el-tag--danger {
            background: #ef4444;
            color: white;
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 80px 24px;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.3;
      }

      .empty-text {
        font-size: 18px;
        font-weight: 500;
        color: #374151;
        margin-bottom: 8px;
      }

      .empty-description {
        font-size: 14px;
        color: #64748b;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .history-content {
    margin: 16px !important;
  }

  .history-header {
    padding: 16px 20px !important;

    .history-title {
      font-size: 18px !important;
    }

    .back-btn {
      font-size: 12px !important;
      padding: 4px 8px !important;
    }
  }

  .history-item {
    padding: 12px 20px !important;

    .record-type {
      font-size: 14px !important;
    }

    .record-date {
      font-size: 12px !important;
    }
  }

  .empty-state {
    padding: 60px 20px !important;

    .empty-icon {
      font-size: 36px !important;
    }

    .empty-text {
      font-size: 16px !important;
    }

    .empty-description {
      font-size: 12px !important;
    }
  }
}
</style>
